package org.correct.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;

import org.correct.servlet.Initializer;

public class PageItem {
	
	// fields
	
	private String title;
	private String description;
	private String url;
	private Calendar fetchTime;		// actually it should be modify time
	
	// getters and setters
	
	public void setTitle(String title) {
		this.title = title;
	}
	public String getTitle() {
		return title;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getDescription() {
		return description;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getUrl() {
		return url;
	}
	public void setFetchTime(Calendar fetchTime) {
		this.fetchTime = fetchTime;
	}
	public Calendar getFetchTime() {
		return fetchTime;
	}
	
	// main methods
	
	public PageItem(String title, String description, String url, Calendar fetchTime) {
		this.setTitle(title);
		this.setDescription(description);
		this.setUrl(url);
		this.setFetchTime(fetchTime);
	}
	
	public PageItem(int doc, ArrayList<String> keywords){
		PageInfoItem item = Initializer.pageInfo.getItem(doc);
		this.setTitle(item.title);
		this.setUrl(item.url);	
		this.setFetchTime(item.fetchTime);
		
		try{
			File file = new File(Initializer.basePath + "text/" + doc + ".txt");
			FileInputStream fis = new FileInputStream(file);
			//System.out.println(doc + " " + item.encoding);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis, item.encoding));
			String text = "";
			for(String str = br.readLine(); str != null; str = br.readLine()){
				text = text.concat(str);
			}
			text = text.toLowerCase();
			String des = "";
			for(int i = 0; i < keywords.size(); i++){
				if(des.indexOf(keywords.get(i)) < 0){
					if(text.indexOf(keywords.get(i)) < 0){
						continue;
					}
					int left = text.indexOf(keywords.get(i)) - 50;
					int right = text.indexOf(keywords.get(i)) + 150;
					if(left < 0){
						left = 0;
					}
					if(right >= text.length()){
						right = text.length() - 1;
					}
					des = des.concat(text.substring(left, right));
					des = des.concat("......");
				}
			}
			this.setDescription(des);
		}catch (Exception e) {
			e.printStackTrace();
			setDescription("获取摘要错误");
		}
	}
}